<template>
  <a-card :bordered="false" :bodyStyle="{ padding: '24px 16px', height: '100%' }">
    <a-button type="primary" @click="createVisible = true" style="margin-bottom:20px;">新建</a-button>
    <s-table
      :columns="columns"
      :data="loadData"
      ref="table"
      class="user_management_table"
      :showPagination="false"
      rowKey="id"
      :indentSize="30"
      :defaultExpandAllRows="true"
    >
      <span slot="actions" slot-scope="text, record">
        <a-tag v-for="(action, index) in record.actionList" :key="index">{{ action.describe }}</a-tag>
      </span>

      <span slot="name" slot-scope="text,record">
        <a-icon
          :component="departmentIcon"
          style="margin:0 20px; font-size:24px;color:#FFD700;"
          v-if="record.type==2"
        ></a-icon>
        <a-icon
          :component="schoolIcon"
          style="margin:0 20px; font-size:24px;"
          v-else-if="record.type==1"
        ></a-icon>
        <span v-else></span>
        <span :title="record.name">{{record.name}}</span>
      </span>

      <span slot="action" slot-scope="text, record">
        <a @click="addModel(record)">添加</a>
        <a-divider type="vertical" />
        <a @click="editModel(record)">编辑</a>
        <a-divider type="vertical" />
        <a :disabled="record.children&&record.children.length>0" @click="del(record)">删除</a>
        <!-- <a-popconfirm title="是否确认删除？" okText="是" cancelText="否" @confirm="del(record)">
          <a :disabled="record.children&&record.children.length>0">删除</a>
        </a-popconfirm>-->
      </span>
    </s-table>
    <!-- 新建 -->
    <a-modal
      title="新建"
      :visible="createVisible"
      :footer="null"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="createF"
        :rules="createRules"
        :model="createForm"
        :label-col="{span:4}"
        :wrapper-col="{span:12}"
      >
        <a-form-model-item label="选择上级" help="支持选择到任意一层，若不选择则默认添加到最外层" :wrapperCol="{span:18}">
          <a-cascader
            :field-names="{ label: 'name', value: 'id', children: 'children' }"
            :options="options"
            v-model="createForm.ids"
            placeholder="请选择新建组织的所属上级"
            changeOnSelect
          />
        </a-form-model-item>
        <a-form-model-item label="类型">
          <a-radio-group v-model="createForm.type">
            <a-radio :value="1">校区</a-radio>
            <a-radio :value="2">部门</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="createForm.name" />
        </a-form-model-item>
        <a-form-model-item label="电话" prop="phone">
          <a-input v-model="createForm.phone" />
        </a-form-model-item>
        <!-- <a-form-model-item label="电话"  v-if="createForm.type==2">
          <a-input v-model="createForm.phone" />
        </a-form-model-item>-->
        <a-form-model-item label="地址" v-if="createForm.type==1" prop="address">
          <a-input v-model="createForm.address" />
        </a-form-model-item>
        <a-form-model-item label="校区类型" v-if="createForm.type==1">
          <a-select :defaultValue="1" v-model="createForm.school_type">
            <a-select-option :value="1">直营</a-select-option>
            <a-select-option :value="2">合作</a-select-option>
            <a-select-option :value="3">加盟</a-select-option>
            <a-select-option :value="4">代理</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="createOk('createF')">确定</a-button>
          <a-button style="margin-left: 10px;" @click="handleCancel">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 编辑 -->
    <a-modal
      :title="`编辑  `+editForm.name"
      :visible="editVisible"
      :footer="null"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="editF"
        :rules="editRules"
        :model="editForm"
        :label-col="{span:4}"
        :wrapper-col="{span:12}"
      >
        <!-- <a-form-model-item label="选择上级" help="支持选择到任意一层，若不选择则默认添加到最外层" :wrapperCol="{span:18}" :disabled="true">
          <a-cascader
            :field-names="{ label: 'name', value: 'id', children: 'children' }"
            :options="options"
            v-model="editForm.ids"
            placeholder="请选择新建组织的所属上级"
            changeOnSelect
          />
        </a-form-model-item>-->
        <a-form-model-item label="类型">
          <span v-if="editForm.type==1">校区</span>
          <span v-if="editForm.type==2">部门</span>
          <!-- <a-radio-group v-model="editForm.type">
            <a-radio :value="1">校区</a-radio>
            <a-radio :value="2">部门</a-radio>
          </a-radio-group>-->
        </a-form-model-item>
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="editForm.name" />
        </a-form-model-item>
        <a-form-model-item label="电话" :prop="editForm.type==1?'phone':''">
          <a-input v-model="editForm.phone" />
        </a-form-model-item>
        <a-form-model-item label="地址" v-if="editForm.type==1" prop="address">
          <a-input v-model="editForm.address" />
        </a-form-model-item>
        <a-form-model-item label="校区类型" v-if="editForm.type==1">
          <a-select :defaultValue="1" v-model="editForm.school_type">
            <a-select-option :value="1">直营</a-select-option>
            <a-select-option :value="2">合作</a-select-option>
            <a-select-option :value="3">加盟</a-select-option>
            <a-select-option :value="4">代理</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="editOk('editF')">确定</a-button>
          <a-button style="margin-left: 10px;" @click="handleCancel">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
import { schoolIcon, departmentIcon } from '@/core/icons'
import { STable } from '@/components'
import { frameWorkList, frameWorkCreate, frameWorkDel, frameWorkEdit } from '@/api/framework'
const columnsArr = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true,
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '校区类型',
    dataIndex: 'school_type',
    key: 'school_type',
    width: 200,
    customRender(school_type, record) {
      if (record.type == 1) {
        return school_type == 1
          ? '直营'
          : school_type == 2
          ? '合作'
          : school_type == 3
          ? '加盟'
          : school_type == 4
          ? '代理'
          : ''
      } else {
        return '--'
      }
    }
  },
  {
    title: '电话',
    dataIndex: 'phone',
    width: 200,
    key: 'phone'
  },
  {
    title: '校区地址',
    dataIndex: 'address',
    ellipsis: true,
    width: 400,
    key: 'address',
    customRender(address, record) {
      if (record.type == 1) {
        return address || '--'
      } else {
        return '--'
      }
    }
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 200,
    align: 'center',
    ellipsis: true,
    key: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    STable
  },
  created() {
    this.getSelect()
  },
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      departmentIcon,
      schoolIcon,
      options: [],
      columns: columnsArr,
      createVisible: false,
      editVisible: false,
      createForm: {
        ids: [],
        name: '',
        type: 1,
        school_type: 1,
        address: '',
        phone: undefined,
        sort: 0
      },
      editRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        phone: [
          { required: true, pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, message: '请输入正确的电话号码！' }
        ],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
      },
      createRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        phone: [
          { required: true, pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, message: '请输入正确的电话号码！' }
        ],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
      },
      editForm: {},
      confirmLoading: false,
      queryParam: {
        school_id: this.$store.state.user.school,
        pageSize: 99999999999
      },
      loadData: parameter => {
        return frameWorkList(this.queryParam)
          .then(res => {
            let obj = Object
            obj.data = res
            return obj
          })
          .catch(err => {
            this.$message.error(err.data.message || '获取数据失败，请刷新页面或稍后再试')
          })
      }
    }
  },
  watch: {
    editVisible(val) {
      if (val == false) {
        this.editForm = {}
      }
    },
    createVisible(val) {
      if (!val) {
        this.createForm = {
          ids: [],
          name: '',
          type: 1,
          school_type: 1,
          address: '',
          phone: undefined,
          sort: 0
        }
      }
    },
    'createForm.type'(val) {
      if (val == 2) {
        this.createRules = {
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          phone: [
            { required: false, pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, message: '请输入正确的手机号码！' }
          ]
        }
      } else {
        this.createRules = {
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          phone: [
            { required: true, pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, message: '请输入正确的手机号码！' }
          ],
          address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
        }
      }
    }
  },
  methods: {
    addModel(e) {
      this.createForm.ids = e.ids
      this.createVisible = true
    },
    editModel(e) {
      this.editForm = JSON.parse(JSON.stringify(e))
      this.editVisible = true
    },
    del(e) {
      let that = this
      this.$confirm({
        title: '提示?',
        content: '是否确认删除？',
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          frameWorkDel(e.id)
            .then(res => {
              that.getSelect()
              that.$message.success('删除成功')
              that.$refs.table.refresh()
            })
            .catch(err => {
              that.$message.error(err.data.message || '删除失败')
            })
        },
        onCancel() {}
      })
    },
    createOk(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.confirmLoading = true
          let params = JSON.parse(JSON.stringify(this.createForm))
          params.school_id = this.$store.state.user.school
          if (params.ids.length > 0) {
            params.parent_id = params.ids[params.ids.length - 1]
          } else {
            params.parent_id = 0
          }
          if (params.type == 1) {
            //添加校区
            frameWorkCreate(params)
              .then(res => {
                this.$message.success('添加成功')
                this.handleCancel()
                this.getSelect()
                this.createForm = {
                  ids: [],
                  name: '',
                  type: 1,
                  school_type: 1,
                  address: '',
                  phone: null,
                  sort: 0
                }
                this.$refs.table.refresh()
              })
              .catch(err => {
                this.confirmLoading = false
                this.$message.error(err.data.message || '添加失败')
              })
          } else {
            //添加部门
            let data = {
              sort: params.sort,
              ids: params.ids,
              parent_id: params.parent_id,
              name: params.name,
              phone: params.phone,
              school_id: params.school_id,
              type: params.type
            }
            frameWorkCreate(data)
              .then(res => {
                this.$message.success('添加成功')
                this.handleCancel()
                this.createForm = {
                  ids: [],
                  name: '',
                  type: 1,
                  school_type: 1,
                  address: '',
                  phone: null,
                  sort: 0
                }
                this.$refs.table.refresh()
                this.getSelect()
              })
              .catch(err => {
                this.confirmLoading = false
                this.$message.error(err.data.message || '添加失败')
              })
          }
        } else {
          return
        }
      })
    },
    editOk(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
            this.confirmLoading = true
            frameWorkEdit(Object.assign(this.editForm, { school_id: this.$store.state.user.school }), this.editForm.id)
              .then(res => {
                this.$message.success('修改成功')
                this.editVisible = false
                this.$refs.table.refresh()
                this.confirmLoading = false
              })
              .catch(err => {
                this.$message.error(err.data.message || '修改失败')
                this.confirmLoading = false
              })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.confirmLoading = false
      this.createVisible = false
      this.editVisible = false
    },
    getSelect() {
      frameWorkList({ school_id: this.$store.state.user.school, pageSize: 99999999999 }).then(res => {
        this.options = res
      })
    }
  }
}
</script>